package com.xulinhao.web;/**
 * @author xulinhao
 * @create 2021-05-28 9:16
 */

import com.xulinhao.service.UserService;
import com.xulinhao.service.impl.UserServiceImpl;
import com.xulinhao.pojo.User;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @Author xlh
 * @packagename: com.xulinhao.web
 * @classname: RegistServlet
 * @Description:
 * @Date 2021/5/28
 */
public class RegistServlet extends HttpServlet {

    private UserService userService = new UserServiceImpl();
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //1 获取请求的参数
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        String email = req.getParameter("email");
        String code = req.getParameter("code");
        //2 检查验证码是否正确 === 目前先要求验证码为:abcde
        if ("abcde".equalsIgnoreCase(code)){
            //正确
            //3 检查用户名是否可用
            if (userService.existsUsername((username))){
                //不可用则跳回注册页面
                System.out.println("用户名已存在!");

                //把回显信息,保存到request域中
                req.setAttribute("msg","用户名已存在!");
                req.setAttribute("username",username);
                req.setAttribute("email",email);

                //跳回注册页面
                req.getRequestDispatcher("/pages/user/regist.jsp").forward(req,resp);
            }else {
                //可用则调用service保存到数据库
                userService.registUser(new User(null,username,password,email));
                //跳到注册成功页面regist_success.html
                req.getRequestDispatcher("/pages/user/regist_success.jsp").forward(req,resp);
            }
        }else {
            //错误,则调回注册页面
            //把回显信息,保存到request域中
            req.setAttribute("msg","验证码错误!");
            req.setAttribute("username",username);
            req.setAttribute("email",email);
            System.out.println("验证码错误");
            req.getRequestDispatcher("/pages/user/regist.jsp").forward(req,resp);
        }
    }
}
